import React, {PureComponent, Fragment} from 'react';
import {PermissionsContext, InitDataContext} from './contexts';
import {Row, Col, Form, Card, Table, Button} from 'antd';
import {Link} from 'react-router-dom';
import {FORM_OPTIONS, TABLE, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT,
    DATETIME_FORMAT, DATE_FORMAT, FIXED_COLUMN_WIDTH, FORM_ROW_OPTIONS} from '../constants';
import {formatMessage, language} from './intl';
import TextInput from 'Shared/components/TextInput';
import DateRangePicker from 'Shared/components/DateRangePicker';
import TagSelect from 'Shared/components/TagSelect';
import WrappedSelect from '../common/WrappedSelect';
import {warrantyPolicyStatus, warrantyPolicyType, dealerType} from '../Enum';
import styles from './style.css';
import routes from './routes';
import {formatDateTime, conventEnumValueToString} from '../utils';
import {isHavePermission} from './utils';
import {PERMISSIONS} from './constants';
import DropdownMenu from 'Shared/components/DropdownMenu';
import {formatNumber} from '../common/localize';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
export const dealerConditions = {
    type: dealerType.总代
};
const ButtonGroup = Button.Group;
const FormItem = Form.Item;

export default class QueryPage extends PureComponent {
    componentDidMount() {
        const state = this.props.location.state;
        if(state && state.query)
            this.props.handleFormQuery();
    }
    onSelectDealer = (data = {}) => {
        this.props.handleFilterChange(data.id, 'dealerId');
        this.props.handleFilterChange(data.code, 'dealerCode');
        this.props.handleFilterChange(data.name, 'dealerName');
    }
    render() {
        const {formData, tableData, pagination, isFetching, message, loading} = this.props;
        const {dealerId, dealerCode, dealerName} = formData;

        const dealerInfo = dealerId ? {
            id: dealerId,
            code: dealerCode,
            name: dealerName
        } : null;
        const generateColumns = pagePermissions => [
            {
                title: formatMessage({
                    id: 'queryPage.code',
                    defaultMessage: '编号'
                }),
                dataIndex: 'code',
                sorter: true,
                render: (text, record) => (
                    <Link key="detail" to={routes.detail.format(record.warrantyPolicyId)}>
                        {text}
                    </Link>
                )
            },
            {
                title: formatMessage({
                    id: 'queryPage.name',
                    defaultMessage: '名称'
                }),
                dataIndex: 'name',
            },
            {
                title: formatMessage({
                    id: 'queryPage.brandCode',
                    defaultMessage: '品牌'
                }),
                dataIndex: 'brandCode',
                render: (text, record) => `(${record.brandCode})${record.brandName}`
            },
            {
                title: formatMessage({
                    id: 'queryPage.dealerCode',
                    defaultMessage: '总代'
                }),
                dataIndex: 'dealerCode',
                render: (text, record) => `(${record.dealerCode})${record.dealerName}`
            },
            {
                title: formatMessage({
                    id: 'queryPage.country',
                    defaultMessage: '国家'
                }),
                dataIndex: 'country'
            },
            {
                title: formatMessage({
                    id: 'queryPage.startTime',
                    defaultMessage: '启用日期'
                }),
                dataIndex: 'startTime',
                sorter: true,
                render: text => formatDateTime(text, DATETIME_FORMAT),
            },
            {
                title: formatMessage({
                    id: 'queryPage.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                render: text => conventEnumValueToString(warrantyPolicyStatus, text)
            },
            {
                title: formatMessage({
                    id: 'queryPage.warrantyPolicyType',
                    defaultMessage: '类型'
                }),
                dataIndex: 'warrantyPolicyType',
                sorter: true,
                render: text => conventEnumValueToString(warrantyPolicyType, text)
            },
            {
                title: formatMessage({
                    id: 'queryPage.warrantyMileage',
                    defaultMessage: '索赔里程'
                }),
                dataIndex: 'warrantyMileage',
                render: text => formatNumber(text)
            },
            {
                title: formatMessage({
                    id: 'queryPage.warrantyMonth',
                    defaultMessage: '索赔月份'
                }),
                dataIndex: 'warrantyMonth',
                render: text => formatNumber(text)
            },
            {
                title: formatMessage({
                    id: 'queryPage.saleStartDate',
                    defaultMessage: '发车开始时间'
                }),
                dataIndex: 'saleStartDate',
                render: text => formatDateTime(text, DATE_FORMAT),
            },
            {
                title: formatMessage({
                    id: 'queryPage.saleEndDate',
                    defaultMessage: '发车结束时间'
                }),
                dataIndex: 'saleEndDate',
                render: text => formatDateTime(text, DATE_FORMAT),
            },
            {
                title: formatMessage({
                    id: 'queryPage.creatorName',
                    defaultMessage: '创建人'
                }),
                dataIndex: 'creatorName',
            },
            {
                title: formatMessage({
                    id: 'queryPage.createTime',
                    defaultMessage: '创建时间'
                }),
                dataIndex: 'createTime',
                sorter: true,
                render: text => formatDateTime(text, DATETIME_FORMAT),
            },
            {
                title: formatMessage({
                    id: 'queryPage.tablePanel.column.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (t, r) => {
                    const menus = [
                        {
                            id: PERMISSIONS.update,
                            children: (
                                <Link key="update" to={routes.update.format(r.warrantyPolicyId)}>
                                    {formatMessage({
                                        id: 'queryPage.tablePanel.operation.update',
                                        defaultMessage: '编辑'
                                    })}
                                </Link>
                            ),
                            hidden: !isHavePermission(PERMISSIONS.update, pagePermissions, r.options)
                        },
                    ];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            }
        ];

        return (
            <Fragment>
                <div className={styles.card_margin}>
                    <Card className="form-standard">
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={formatMessage({
                                        id: 'queryPanel.dealerId',
                                        defaultMessage: '总代'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <DealerSelectPanel
                                        value={dealerInfo}
                                        conditions={dealerConditions}
                                        onSelect={this.onSelectDealer} />
                                </FormItem>
                            </Col>

                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'queryPage.brandId',
                                    defaultMessage: '品牌'
                                })} {...FORM_OPTIONS.item} >
                                    <InitDataContext.Consumer>
                                        {
                                            brands => (
                                                <WrappedSelect
                                                    name="brandId"
                                                    allowClear
                                                    options={brands}
                                                    value={formData.brandId}
                                                    onChange={this.props.handleFilterChange} />
                                            )
                                        }
                                    </InitDataContext.Consumer>
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({id: 'queryPage.code',
                                    defaultMessage: '编号'})} {...FORM_OPTIONS.item} >
                                    <TextInput
                                        name="code"
                                        value={formData.code}
                                        onPressEnter={this.props.handleFilterPressEnter}
                                        onBlur={this.props.handleFilterChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({id: 'queryPage.name',
                                    defaultMessage: '名称'})} {...FORM_OPTIONS.item} >
                                    <TextInput
                                        name="name"
                                        value={formData.name}
                                        onPressEnter={this.props.handleFilterPressEnter}
                                        onBlur={this.props.handleFilterChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({id: 'queryPage.startTime',
                                    defaultMessage: '启用日期'})} {...FORM_OPTIONS.item} >
                                    <DateRangePicker
                                        name="startTime"
                                        value={formData.startTime}
                                        onChange={this.props.handleFilterChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({id: 'queryPage.warrantyPolicyType',
                                    defaultMessage: '类型'})} {...FORM_OPTIONS.item} >
                                    <WrappedSelect
                                        name="warrantyPolicyType"
                                        allowClear
                                        options={warrantyPolicyType.toList(language)}
                                        value={formData.warrantyPolicyType}
                                        onChange={this.props.handleFilterChange} />
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col>
                                <FormItem
                                    label={formatMessage({
                                        id: 'queryPage.queryPanel.form.status',
                                        defaultMessage: '状态'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}>
                                    <TagSelect
                                        name="status"
                                        value={formData.status}
                                        options={warrantyPolicyStatus.toList(language)}
                                        onChange={this.props.handleFilterChange} />
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Button type="primary" onClick={this.props.handleFormQuery} loading={isFetching}>
                                {formatMessage({
                                    id: 'queryPage.btn.search',
                                    defaultMessage: '查询'
                                })}
                            </Button>
                            <Button onClick={this.props.clearFormData}>
                                {formatMessage({
                                    id: 'queryPage.btn.reset',
                                    defaultMessage: '重置'
                                })}
                            </Button>
                            <div
                                style={{
                                    float: 'right'
                                }}>
                                <PermissionsContext.Consumer>
                                    {
                                        pagePermissions =>
                                            <Fragment>
                                                {
                                                    isHavePermission(PERMISSIONS.enable, pagePermissions) && (
                                                        <Button key="enable" href={`#${routes.enable.url()}`}>
                                                            {formatMessage({
                                                                id: 'queryPage.queryPanel.btn.enable',
                                                                defaultMessage: '生效'
                                                            })}
                                                        </Button>
                                                    )
                                                }
                                                {
                                                    isHavePermission(PERMISSIONS.abandon, pagePermissions) && (
                                                        <Button key="abandon" href={`#${routes.abandon.url()}`}>
                                                            {formatMessage({
                                                                id: 'queryPage.queryPanel.btn.abandon',
                                                                defaultMessage: '作废'
                                                            })}
                                                        </Button>
                                                    )
                                                }
                                                {
                                                    isHavePermission(PERMISSIONS.add, pagePermissions) && (
                                                        <Button
                                                            type="primary"
                                                            href={`#${routes.add.url()}`}>
                                                            {formatMessage({
                                                                id: 'queryPage.btn.add',
                                                                defaultMessage: '新增'
                                                            })}
                                                        </Button>
                                                    )
                                                }
                                            </Fragment>
                                    }
                                </PermissionsContext.Consumer>
                            </div>
                        </Row>
                    </Card>
                </div>
                <div className={styles.card_margin}>
                    <Card>
                        <PermissionsContext.Consumer>
                            {pagePermissions =>
                                <Table
                                    className={`white-space-nowrap ${styles.tableCursor}`}
                                    rowKey="id"
                                    dataSource={tableData.content}
                                    columns={generateColumns(pagePermissions)}
                                    loading={isFetching || loading}
                                    pagination={pagination}
                                    onChange={this.props.handleTableChange}
                                    {...TABLE}
                                    locale={{
                                        emptyText: message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                                    }} />
                            }
                        </PermissionsContext.Consumer>
                    </Card>
                </div>
            </Fragment>
        );
    }
}
